/**
 * 描述: 连接mysql模块
 * 作者: Jack Chen
 * 日期: 2020-06-20
*/


const mysql = require('mysql');
const config = require('../db/dbConfig');
const formidable = require('formidable')
const fs = require('fs');
const path = require('path');
const request = require('request');
// 创建连接池
const pool = mysql.createPool(config);

// 新建查询连接
function querySql(sql) { 
  return new Promise((resolve, reject) => {
    try {
      pool.getConnection((err, conn) => {
        if( err){
          reject(err);
          return;
        }
        conn.query(sql, (err, res) => {
          // 释放连接
          conn.release();
          if (err) {
            reject(err);
          } else {
            resolve(res);
          }
        })
      });
    } catch (e) {
      reject(e);
    }
  })
}

// 查询一条语句
function queryOne(sql) {
  return new Promise((resolve, reject) => {
    querySql(sql).then(res => {
      console.log('res===',res)
      if (res && res.length > 0) {
        resolve(res[0]);
      } else {
        resolve(null);
      }
    }).catch(err => {
      reject(err);
    })
  })
}

function formatTime(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1; // 月份从0开始，需要加1
  var day = date.getDate();
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
}

function innerUploadFile(req) { 
  return new Promise((resolve, reject) => {
    const form = new formidable.IncomingForm();
    form.uploadDir = path.join(__dirname, '../public/upload/');
    form.maxFieldsSize = 200 * 1024 * 1024;
    form.parse(req, (err, fields, files) => {
      if (err) {
        reject(err);
      } else {
        if( files.file && files.file.length > 0){
          let fileItem = files.file[0];
          // 文件重命名
          let extName = path.extname(fileItem.originalFilename);
          let newFilename = fileItem.filepath + extName;
          fs.renameSync(fileItem.filepath, newFilename);
          resolve({filepath:newFilename, newFilename:'/upload/'+fileItem.newFilename+extName});
        }else{
          reject('No file uploaded');
        }
      }
    })
  })
}

function downloadFile(url, dest) {
  return new Promise((resolve, reject) => {
    request.head(url, (err, res, body) => {
      if (err) {
        return reject(err);
      }

      // 检查响应状态码是否为200
      if (res.statusCode !== 200) {
        return reject(new Error('Failed to fetch file, status code: ' + res.statusCode));
      }

      // 创建一个可写流
      const file = fs.createWriteStream(dest);

      // 发起GET请求，并将响应的数据流通过管道写入到文件中
      request(url)
        .pipe(file)
        .on('close', () => {
          console.log('File has been downloaded successfully ' + dest);
          resolve(dest);
        })
        .on('error', err => {
          console.error('Error downloading file:', err);
          // 确保在出错时关闭文件流
          file.close();
          reject(err);
        });
    });
  });
}

// 定义一个函数，该函数在指定的毫秒数后执行
function waitFor(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

module.exports = {
  querySql,
  queryOne,
  formatTime,
  innerUploadFile,
  downloadFile,
  waitFor
}